import { useReducer } from "react";

const initValue = {
  name: '夏天',
  age: 18
}

function reducer(state, action) {
  const { type, payload } = action
  switch (type) {
    case 'addAge':
      return { ...state, age: state.age + payload }
    case 'changeUser':
      return { ...payload }
    default:
      return state
  }
}

export default function UseReducerDemo() {
  const [state, dispatch] = useReducer(reducer, initValue)

  return (
    <>
      <h1>useReducer的使用</h1>
      <div>用户名:{state.name},年龄:{state.age}</div>
      <button onClick={() => dispatch({ type: 'addAge', payload: 2 })}>添加年龄</button>
      <button onClick={() => dispatch({ type: 'changeUser', payload: { name: '周一帆', age: 18 } })}>切换用户</button>

    </>
  )
}